package com.training.controller;

import com.training.entity.Course;
import com.training.entity.Student;
import com.training.entity.User;
import com.training.service.CourseService;
import com.training.service.PurchaseRecordService;
import com.training.service.ShoppingCartService;
import com.training.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal; // 1. Import BigDecimal for precise calculations
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/student/cart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private PurchaseRecordService purchaseRecordService;

    @GetMapping
    public String viewCart(HttpSession session, Model model) {
        Object userIdObj = session.getAttribute("loggedInUserId");
        if (userIdObj == null) {
            return "redirect:/login";
        }
        Long studentId = (Long) session.getAttribute("loggedInStudentId");
        if (studentId == null) {
            return "redirect:/login";
        }

        List<Course> cartItems = shoppingCartService.getCartItemsByStudentId(studentId);
        model.addAttribute("cartItems", cartItems);

        // --- CORE FIX: Use BigDecimal for total price calculation ---
        // 2. Change the total price variable type to BigDecimal
        BigDecimal totalCartPrice = BigDecimal.ZERO;
        if (cartItems != null) {
            for (Course item : cartItems) {
                // 3. Use the .add() method for accurate addition
                if (item.getCouPrice() != null) {
                    totalCartPrice = totalCartPrice.add(item.getCouPrice());
                }
            }
        }
        model.addAttribute("totalCartPrice", totalCartPrice);

        return "student-cart";
    }

    @PostMapping("/purchase/cart")
    @ResponseBody
    public String checkoutCart(@RequestBody List<Long> courseIds,
                               HttpSession session) {
        Long studentId = (Long) session.getAttribute("loggedInStudentId");

        if (studentId == null) {
            return "{\"status\":\"error\", \"message\":\"请先登录！\"}";
        }

        if (courseIds == null || courseIds.isEmpty()) {
            return "{\"status\":\"error\", \"message\":\"结算失败，未选择任何课程！\"}";
        }

        try {
            boolean purchaseSuccess = purchaseRecordService.batchPurchaseCoursesFromCart(studentId, courseIds);

            if (purchaseSuccess) {
                shoppingCartService.clearCartByStudentId(studentId);
                return "{\"status\":\"success\", \"message\":\"结算成功！课程已添加到您的账户。\"}";
            } else {
                return "{\"status\":\"error\", \"message\":\"结算失败，原因可能是积分不足或课程已被购买。\"}";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "{\"status\":\"error\", \"message\":\"结算过程中发生错误：" + e.getMessage() + "\"}";
        }
    }

    @PostMapping("/remove/{courseId}")
    public String removeCourseFromCart(@PathVariable("courseId") Long courseId,
                                       HttpSession session,
                                       RedirectAttributes redirectAttributes) {

        Long studentId = (Long) session.getAttribute("loggedInStudentId");
        if (studentId == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        boolean success = shoppingCartService.removeCourseFromCart(studentId, courseId);
        if (success) {
            redirectAttributes.addFlashAttribute("message", "课程移除成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "移除课程失败，请稍后重试。");
        }
        return "redirect:/student/cart";
    }

    @PostMapping("/clear")
    public String clearShoppingCart(HttpSession session, RedirectAttributes redirectAttributes) {
        Long studentId = (Long) session.getAttribute("loggedInStudentId");
        if (studentId == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录！");
            return "redirect:/login";
        }
        boolean success = shoppingCartService.clearCartByStudentId(studentId);
        if (success) {
            redirectAttributes.addFlashAttribute("message", "购物车已清空！");
        } else {
            redirectAttributes.addFlashAttribute("error", "清空购物车失败，您的购物车可能已为空。");
        }
        return "redirect:/student/cart";
    }

    @PostMapping("/add/{courseId}")
    public String addCourseToCart(@PathVariable("courseId") Long courseId,
                                  HttpSession session,
                                  RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生资料，无法添加课程到购物车。");
            return "redirect:/student/courses/browse";
        }
        try {
            boolean success = shoppingCartService.addCourseToCart(student.getId(), courseId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程已成功加入购物车！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "课程已在购物车中。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "添加课程到购物车失败：" + e.getMessage());
        }
        return "redirect:/student/courses/browse";
    }
}